package inglar.autotc.server;

import java.util.Vector;

import inglar.autotc.client.HostService;
import inglar.autotc.shared.db.Actions;
import inglar.autotc.shared.db.Templates;

import javax.servlet.http.HttpServletRequest;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Implementation for ConsoleService.
 * @see inglar.autotc.client.HostService
 * @author Lee
 */
@SuppressWarnings("deprecation")
public class HostServiceImpl extends RemoteServiceServlet implements HostService {

	private static final long serialVersionUID = -7434714297852562632L;
	
	private static final String qcmd = "java -jar $AUTOTC_HOME/autotc.jar "; 
	
	/**
	 * Implementation for {@code ConsoleService.exec(String cmd)}
	 * @param cmd the command to be run
	 * @throws RuntimeException
	 */
	@Override
	public String exec(String cmd) throws RuntimeException {
		
		return Host.exec(cmd);
	}

	/**
	 * Implementation for {@code ConsoleService.scriptase(String cmd)}
	 * @param cmd the command to be run
	 * @throws RuntimeException
	 */
	@Override
	public String scriptase(String cmd) throws RuntimeException {
		
		return Host.scriptase(cmd, getThreadLocalRequest());
	}
	
	/**
	 * Checks if this application is installed correctly.
	 * @return a non-emtpy string if installation is not successful, an empty string otherwise   
	 * @throws RuntimeException
	 */
	@Override
	public String checkInstallation() throws RuntimeException {
		
		String temp = ""; //scriptase("sudo echo $QONTROLII_HOME");
//		
//		String prefix = "sudo -E ";
//
//		temp = scriptase(prefix + "echo $QONTROLII_HOME");
//		if(temp.isEmpty()) return "ERROR W001: Environment variable 'QONTROLII_HOME' on host system not set.";
//		if(!temp.startsWith("/")) return "ERROR W002: Path in environment variable 'QONTROLII_HOME' must be absolute.";
//
//		temp = scriptase(prefix + "ls $QONTROLII_HOME/qontrolii-daemon.jar");
//		if(temp.contains("No such file")) return "ERROR W003: Application file qontrolii-daemon.jar not found.";
//		
//		temp = scriptase(prefix + "$QONTROLII_HOME/qontrolii-daemon.jar -check");
		
		try {
			temp = Host.getCmd();
			temp = exec(temp + " -check");
			temp.trim();
		} catch (Throwable caught) {
			temp = caught.getMessage();
		}
		
		return temp;
	}
	
	@Override
	public String login(String username, String password) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-u -in " + username + " " + password + " " + jsessionid;
		return Host.scriptase(cmd, req);
	}

	@Override
	public String[] getDeviceList(String userid) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -devicelist";
		String t = Host.scriptase(cmd, req).trim();
		if(t.startsWith("ERROR")) throw new RuntimeException(t);
		if(t.contains("No configurable devices found")) return new String[0];
		return t.trim().split(",");
	}

	@Override
	public String[] getDeviceConfig(String userid, String device) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -getscript " + device;
		String t = Host.scriptase(cmd, req).trim();
		if(t.startsWith("ERROR")) throw new RuntimeException(t);
		if(t.contains("No script found")) return new String[0];
		return t.trim().split("#");
	}

	@Override
	public String setDeviceConfig(String userid, String device, String settingid, String script) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		if(settingid.isEmpty()) settingid = null;
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -setscript " + device +
				" " + settingid + " '" + script + "'";
		String t = Host.scriptase(cmd, req).trim();
		if(t.startsWith("ERROR")) throw new RuntimeException(t);
		return t;
	}

	@Override
	public String[] getTemplateList(String userid, String device) {
		String[] retval = null;
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -gettemplatelist " + device;
		String t = Host.scriptase(cmd, req);
		if(t.trim().isEmpty()) retval = new String[0];
		else retval = t.split("\n");
		return retval;
	}

	@Override
	public String setTemplate(String userid, String device, String name, String script) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -settemplate " + device + " " + name + " '" + script + "'";
		String t = Host.scriptase(cmd, req);
		return t;
	}

	@Override
	public String[] getClientList(String userid) {
		String[] retval = null;
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -getclientlist";
		String t = Host.scriptase(cmd, req).trim();
		if(t.isEmpty()) retval = new String[0];
		if(t.startsWith("ERROR")) retval = new String[0];
		else retval = t.split("\n");
		return retval;
	}

	@Override
	public String setClient(String userid, String ipaddr, Integer port) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -setclient " + ipaddr + " " + port.intValue();
		String t = Host.scriptase(cmd, req);
		return t;
	}

	@Override
	public String[] netstat(String userid, String ipaddress, Integer port) {
		String[] retval = null;
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -netstat " + ipaddress + " " + port;
		String t = Host.scriptase(cmd, req);
		if(t.trim().isEmpty()) retval = new String[0];
		else retval = t.split("\n");
		return retval;
	}

	@Override
	public String deleteClient(String userid, String ipaddr, Integer port) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -delclient " + ipaddr + " " + port.intValue();
		String t = Host.scriptase(cmd, req);
		return t;
	}

	@Override
	public String[] getActionList(String userid) {
		String[] retval = null;
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -getactionlist";
		String t = Host.scriptase(cmd, req);
		if(t.trim().isEmpty() || t.trim().startsWith("ERROR")) retval = new String[0];
		else retval = t.split("\n");
		return retval;
	}

	@Override
	public String deleteAction(String userid, String actionid) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -delaction " + actionid;
		String t = Host.scriptase(cmd, req);
		return t;
	}

	@Override
	public Templates[] getTemplateList(String userid) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String t = null;
		String cmd = "-w " + userid + " " + jsessionid + " -gettemplatelist";
		try {
			t = Host.run(cmd);
		} catch(Exception e) {
			throw new RuntimeException("Unable to run command: " + cmd, e);
		}
		if(t.startsWith("ERROR")) {
			throw new RuntimeException(t);
		}
		String[] u = t.split("\n");
		Vector<Templates> v = new Vector<Templates>();
		for(int i = 0; i < u.length; i++) {
			String w = Templates.head + u[i].trim() + Templates.tail;
			try {
				Templates x = new Templates(w);
				v.add(x);
			} catch (Exception e) {
				
			}
		}
		Templates[] retval = new Templates[v.size()];
		if(v.size() != 0) v.copyInto(retval);
		return retval;
	}

	@Override
	public void setAction(String userid, Actions action) {
		HttpServletRequest req = getThreadLocalRequest();
		String jsessionid = req.getSession().getId();
		String cmd = qcmd + "-w " + userid + " " + jsessionid + " -setaction " +
				"\"" + action.getPrio() + "\" \"" + action.getDetect() + "\" \"" +
				action.getAction() + "\"";
		try {
			String t = Host.scriptase(cmd, req);
			if(!t.isEmpty()) throw new RuntimeException(t);
		} catch (Exception e) {
			throw new RuntimeException("cannot run", e);
		}
	}
}
